 //
//  ZWComposeViewController.swift
//  ZWWeibo
//
//  Created by flyiron on 16/4/25.
//  Copyright © 2016年 flyiron. All rights reserved.
//

import UIKit
import SVProgressHUD
 
class ZWComposeViewController: UIViewController {
    let pictureTopMargin:CGFloat = 40
    var sizeH:CGFloat?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
    }
    
    private func setupUI(){
        view.backgroundColor = UIColor.whiteColor()
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(ZWComposeViewController.back))
        navigationItem.titleView = titleView
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendBTN)
        navigationItem.rightBarButtonItem?.enabled = false
        //添加控件
        view.addSubview(textView)
        view.addSubview(composeToolBar)
        textView.addSubview(pictureView)
        textView.becomeFirstResponder()
        
        //设置约束
        textView.snp_makeConstraints { (make) in
            make.edges.equalTo(self.view)
        }
        composeToolBar.snp_makeConstraints { (make) in
            make.leading.bottom.trailing.equalTo(self.view)
            make.height.equalTo(44)
        }
        pictureView.snp_makeConstraints { (make) in
            make.top.equalTo(self.sizeH! + topMargin*2 + pictureTopMargin)
            make.leading.equalTo(5)
            make.width.equalTo(textView).offset(-10)
            make.height.equalTo(pictureView.snp_width)
        }
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ZWComposeViewController.keyboardChageFrame(_:)), name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    @objc private func keyboardChageFrame(noti:NSNotification){
        let endFrame = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
//        print(endFrame.origin.y-SCREENH)
        composeToolBar.snp_updateConstraints { (make) in
            make.bottom.equalTo(endFrame.origin.y-SCREENH)
        }
        UIView.animateWithDuration(0.25) { 
            self.view.layoutIfNeeded()
        }
    }
    
    @objc private func back(){
        self.dismissViewControllerAnimated(true, completion: nil)
        textView.resignFirstResponder()
    }
    //发送微博
    @objc private func send(){
        if pictureView.images?.count == 0 {
            sendTextWeibo()
        }else{
            sendImageWeibo()
        }
        
    }
    private func sendTextWeibo(){
        let url:String = "https://api.weibo.com/2/statuses/update.json"
        let parmas = [
            "access_token":ZWUserInfoViewModel.sharedViewModel.accessToken,
            "status":textView.text
        ]
        ZWNetworkTools.sharedTools.request(.Post, urlString: url, parameters: parmas) { (responseObject, error) in
            if error != nil{
                SVProgressHUD.showErrorWithStatus("发送失败")
                print(error)
            }else{
                SVProgressHUD.showSuccessWithStatus("发送成功")
                self.back()
            }
        }
    }
    private func sendImageWeibo(){
        let url = "https://upload.api.weibo.com/2/statuses/upload.json"
        let parmas = [
            "access_token":ZWUserInfoViewModel.sharedViewModel.accessToken,
            "status":textView.text
        ]
        
        ZWNetworkTools.sharedTools.POST(url, parameters: parmas, constructingBodyWithBlock: { (FormData) in
            let data = UIImagePNGRepresentation(self.pictureView.images!.first!)
                FormData.appendPartWithFileData(data!, name: "pic", fileName: "haha", mimeType: "application/octet-stream")
            }, success: { (_, response) in
                SVProgressHUD.showSuccessWithStatus("发送成功")
                self.back()
                print(response)
            }) { (_, error) in
                SVProgressHUD.showErrorWithStatus("发送失败")
                print(error)

        }
        
    }
    private func pickPicture(){
        let vc = UIImagePickerController()
        
        vc.delegate = self
        
        self.presentViewController(vc, animated: true, completion: nil)
        
    }
    
    private func switchKeyBoard(){
        textView.inputView = textView.inputView == nil ? emoticonKeyboardView : nil
        textView.reloadInputViews()
        if !textView.becomeFirstResponder() {
            textView.becomeFirstResponder()
        }
    }
    // MARK: - 懒加载控件 点击toolbar按钮执行的方法
    private lazy var composeToolBar:ZWComposeToolBar = {
        let toolbar = ZWComposeToolBar(frame: CGRectZero)
        toolbar.toolbarClosure = {(type:ZWToolbarButtonType) in
            print(type)
            //case Picture = 0 , Mention, Trend, Emoticon, Add
            switch type {
            case ZWToolbarButtonType.Picture:
                self.pickPicture()
                break
            case ZWToolbarButtonType.Mention:
                break
            case ZWToolbarButtonType.Trend:
                break
            case ZWToolbarButtonType.Emoticon:
                self.switchKeyBoard()
                break
            case ZWToolbarButtonType.Add:
                break
            }
        }
        return toolbar
    }()
    
    private lazy var emoticonKeyboardView:ZWEmoticonKeyBoard = {
        let view = ZWEmoticonKeyBoard()
        view.bounds = CGRectMake(0, 0, SCREENW, 216)
        return view
    }()
    
    private lazy var pictureView:ZWComposePictureView = {
        let view = ZWComposePictureView(frame: CGRectZero, collectionViewLayout: UICollectionViewFlowLayout())
        view.backgroundColor = UIColor.clearColor()
        view.pickImageClosure = {[weak self] in
                self!.pickPicture()
        }
        
        return view
    }()
    
    private lazy var textView:ZWComposeTextView = {
        let textView = ZWComposeTextView()
        let label = UILabel(textColor: UIColor.redColor(), fontSize: 20)
        label.text = "甜到掉牙了"
        label.sizeToFit()
        let size = label.bounds
        self.sizeH = size.height
        textView.placeholderLabelText = label.text
        textView.font = label.font
        textView.delegate = self
        textView.alwaysBounceVertical = true
        textView.keyboardDismissMode = .OnDrag
        return textView
    }()
    
    private lazy var sendBTN:UIButton = {
        let rightButton = UIButton(textColor: UIColor.whiteColor(), fontSize: 14)
        rightButton.addTarget(self, action: #selector(ZWComposeViewController.send), forControlEvents: UIControlEvents.TouchUpInside)
        rightButton.setTitle("发送", forState: UIControlState.Normal)
        rightButton.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Disabled)
        rightButton.setBackgroundImage(UIImage(named: "common_button_orange"), forState: UIControlState.Normal)
        rightButton.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: UIControlState.Highlighted)
        
        rightButton.setTitleColor(UIColor.grayColor(), forState: UIControlState.Disabled)
        
        rightButton.frame.size = CGSize(width: 45, height: 28)
        
        return rightButton
    }()
    private lazy var titleView:UILabel = {
        let label = UILabel(textColor: UIColor.darkGrayColor(), fontSize: 20)
        label.numberOfLines = 0
        label.textAlignment = .Center
        if let name = ZWUserInfoViewModel.sharedViewModel.userModel?.name {
            let text = "发微博\n\(name)"
            let range = (text as NSString).rangeOfString(name)
            let attrText = NSMutableAttributedString(string: text)
            attrText.addAttributes([NSForegroundColorAttributeName: UIColor.lightGrayColor(), NSFontAttributeName: UIFont.systemFontOfSize(14)], range: range )
            label.attributedText = attrText
        }else{
            label.text = "发微博"
        }
        label.sizeToFit()
        return label
    }()
}

 // MARK: - TextView,pickerView代理方法
 extension ZWComposeViewController:UITextViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    func textViewDidChange(textView: UITextView) {
//        print(textView.contentSize.height)
        pictureView.snp_updateConstraints { (make) in
           make.top.equalTo(textView.contentSize.height + pictureTopMargin)
        }
        sendBTN.enabled = textView.hasText()
    }
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        pictureView.setImage(image.scaleImageWithWidth(600))
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
 }
 
